package com.ms.content.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ms.common.utils.R;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ms.common.utils.PageUtils;
import com.ms.common.utils.Query;

import com.ms.content.dao.AdmsDao;
import com.ms.content.entity.AdmsEntity;
import com.ms.content.service.AdmsService;


@Service("admsService")
public class AdmsServiceImpl extends ServiceImpl<AdmsDao, AdmsEntity> implements AdmsService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient client;


    @Override
    public R queryPage(Map<String, Object> params) throws InterruptedException {

        String pagee = (String) params.get("page");
        String size = (String) params.get("limit");
        RLock lock = client.getLock("cateRWlock");

        //获取锁
        boolean b = lock.tryLock(30, 10, TimeUnit.SECONDS);
        try {
            if (b){
                //判断是否为缓存第一页
                if (Integer.parseInt(pagee) != 1) {
                    System.out.println("查询一次数据库页数为" + pagee);

                    IPage<AdmsEntity> pageee = this.page(
                            new Query<AdmsEntity>().getPage(params),
                            new QueryWrapper<AdmsEntity>()
                    );
                    //将库存缓存到redis中
                    List<HashMap<Integer, Integer>> hashMaps = new ArrayList<>();
                    for (AdmsEntity admsEntity : pageee.getRecords()) {
                        HashMap<Integer, Integer> integerIntegerHashMap = new HashMap<Integer, Integer>();
                        integerIntegerHashMap.put(admsEntity.getId(), admsEntity.getMsCount());
                        hashMaps.add(integerIntegerHashMap);
                        //设置库存过期时间 10分钟
//                            stringRedisTemplate.opsForValue().set(admsEntity.getId()+"", admsEntity.getMsCount()+"",10,TimeUnit.MINUTES);
                    }
                    stringRedisTemplate.opsForValue().set("count",JSON.toJSONString(hashMaps),10,TimeUnit.MINUTES);
                    return R.ok().put("page", new PageUtils(pageee));
                } else {
                    String o = stringRedisTemplate.opsForValue().get("goodsList" + 1);
                    if (!StringUtils.isEmpty(o)) {
                        //获取最后一个逗号的位置
                        int i = o.lastIndexOf(",");
                        String substringh = o.substring(i + 1);
                        String substringq = o.substring(0, i);
                        //                System.out.println("截取的字符串前" + substringq);
                        //                System.out.println("截取的字符串后" + substringh);
                        List<AdmsEntity> pagess = JSONObject.parseObject(substringq, new TypeReference<List<AdmsEntity>>() {
                        });
                        //将库存缓存到redis中
//                        for (AdmsEntity admsEntity : pagess) {
//                            //设置库存过期时间 10分钟
//                            stringRedisTemplate.opsForValue().set(admsEntity.getId()+"", admsEntity.getMsCount()+"",10,TimeUnit.MINUTES);
//                        }
                        //将库存缓存到redis中
                        List<HashMap<Integer, Integer>> hashMaps = new ArrayList<>();
                        for (AdmsEntity admsEntity : pagess) {
                            HashMap<Integer, Integer> integerIntegerHashMap = new HashMap<Integer, Integer>();
                            integerIntegerHashMap.put(admsEntity.getId(), admsEntity.getMsCount());
                            hashMaps.add(integerIntegerHashMap);
                            //设置库存过期时间 10分钟
//                            stringRedisTemplate.opsForValue().set(admsEntity.getId()+"", admsEntity.getMsCount()+"",10,TimeUnit.MINUTES);
                        }
                        stringRedisTemplate.opsForValue().set("count",JSON.toJSONString(hashMaps),10,TimeUnit.MINUTES);
                        System.out.println("缓存命中");
                        IPage<AdmsEntity> page = new Page<>();
                        page.setRecords(pagess);
                        page.setTotal(Long.parseLong(substringh));
                        return R.ok().put("page", new PageUtils(page));
                    } else {
                        //在redis中没有缓存再去数据库进行查询
                        System.out.println("查数据库");
                        IPage<AdmsEntity> pageee = this.page(
                                new Query<AdmsEntity>().getPage(params),
                                new QueryWrapper<AdmsEntity>()
                        );
                        List<AdmsEntity> records = pageee.getRecords();
                        System.out.println(records);
                        String jsonString = JSONObject.toJSONString(records);
                        String jsonStrings = JSON.toJSONString(records);
                        System.out.println(jsonString);
                        System.out.println(jsonStrings);
                        //将库存缓存到redis中
//                        List<String> strings = new ArrayList<>();
//                        for (AdmsEntity admsEntity : records) {
//                            stringRedisTemplate.opsForValue().set(admsEntity.getId()+"", admsEntity.getMsCount()+"",10,TimeUnit.MINUTES);
//                        }
                        List<HashMap<Integer, Integer>> hashMaps = new ArrayList<>();
                        for (AdmsEntity admsEntity : records) {
                            HashMap<Integer, Integer> integerIntegerHashMap = new HashMap<Integer, Integer>();
                            integerIntegerHashMap.put(admsEntity.getId(), admsEntity.getMsCount());
                            hashMaps.add(integerIntegerHashMap);
                            //设置库存过期时间 10分钟
//                            stringRedisTemplate.opsForValue().set(admsEntity.getId()+"", admsEntity.getMsCount()+"",10,TimeUnit.MINUTES);
                        }
                        stringRedisTemplate.opsForValue().set("count",JSON.toJSONString(hashMaps),10,TimeUnit.MINUTES);
                        //设置过期时间为30分
                        stringRedisTemplate.opsForValue().set("goodsList" + 1, jsonString + "," + pageee.getTotal(), 10, TimeUnit.MINUTES);
                        IPage<AdmsEntity> page = new Page<>();
                        page = pageee;
                        return R.ok().put("page", new PageUtils(page));
                    }
                }
            }else {
                Thread.sleep(100);
            }
        } finally {
            lock.unlock();
        }
//        System.out.println(pagee);
        //自旋
        return queryPage(params);
    }

    @Override
    public AdmsEntity infoxx(Integer id) {
        QueryWrapper<AdmsEntity> wapper = new QueryWrapper<AdmsEntity>().eq("id", id);
        AdmsEntity admsEntity = baseMapper.selectOne(wapper);
        return admsEntity;
    }

    @Override
    public Integer selectCount(Integer id, Integer sid) {
        return baseMapper.sele(id, sid);
    }

}